<?php
/*
 *
 *      tags.plugin.php - v1.0.0 @07.07.2009 22:29:40 CEST
 *
 *      StudioGallery Copyright (C) 2009 Rafal Kusior (spuavick) <spuavick@interia.pl>
 *
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *      -----------------------------------------------------------------------------
 *
 *      Niniejszy program jest wolnym oprogramowaniem - możesz go rozpowszechniać
 *      dalej i/lub modyfikować na warunkach Powszechnej Licencji Publicznej GNU
 *      wydanej przez Fundację Wolnego Oprogramowania, według wersji 2 tej Licencji
 *      lub dowolnej z późniejszych wersji.
 *
 *      Niniejszy program rozpowszechniany jest z nadzieją, iż będzie on użyteczny -
 *      jednak BEZ ŻADNEJ GWARANCJI, nawet domyślnej gwarancji PRZYDATNOŚCI HANDLOWEJ
 *      albo PRZYDATNOŚCI DO OKREŚLONYCH ZASTOSOWAŃ. Bliższe informacje na ten temat
 *      można uzyskać z Powszechnej Licencji Publicznej GNU.
 *
 *      Kopia Powszechnej Licencji Publicznej GNU powinna zostać ci dostarczona
 *      razem z tym programem. Jeżeli nie została dostarczona, odwiedź
 *      <http://www.gnu.org/licenses/>
 */

$plugin_id = basename(__FILE__);

$data['name'] = "Tagi";
$data['desc'] = "Plugin dodający tagi do zdjęć i wpisów, a także rysujący chmurkę tagów.";
$data['author'] = "spuavick";
$data['url'] = "http://www.spuavick.pl/";
$data['version'] = '0.9.0';
$data['options'] = '1'; //


if (plugin_status($plugin_id,$data) == '1' ) {

	global $db;
	add_hook('header','sg_tag_header');
	add_hook('newsitem','sg_tag_newsitem');
	add_hook('photoinfo','sg_tag_photoinfo');
	add_hook('sidebar','sg_tag_cloud_generate');
	add_hook('post','sg_tag_post');
	add_hook('post_save','sg_tag_post');
	add_hook('photo','sg_tag_post');
	add_hook('photo_save','sg_tag_post');

	if ($_GET['options'] && $_GET['options'] == $plugin_id) {
    	add_hook('plugin_options','sg_tag_form_options');
	}
}

if ($_GET['activate'] && $_GET['activate'] == $plugin_id) {

	sg_tag_install();
    add_hook('plugin_info','sg_tag_install_ok');
}



function sg_tag_install_ok() {

	return  '<div class="ok">Wtyczka zainstalowana</div>';
}

function sg_tag_header($head) {

	global $conf;
    $head .= '
    <link rel="stylesheet" type="text/css" href="'.$conf['conf_url'].'plugins/tagi/tags.css" />';
    $tag = sg_tag_get_tag();
    if (is_array($tag)) {
		$tags = join(", ", $tag);
		$head = preg_replace("#<meta\sname=\"keywords\"\scontent=\"(.*?)\"#is","<meta name=\"keywords\" content=\"".$tags.", $1"."\"",$head);
		return $head;
    } else {
	    return $head;
	}
}

function sg_tag_newsitem($new) {

    $tag = sg_tag_get_tag();
    if (is_array($tag)) {
		$new['news_text'] = $new['news_text'].'<div class="tag"><strong>Tagi:</strong> ';
		$i=0;
		while($i<count($tag)) {
			if ( $i+1 == count($tag) ) $end = ''; else $end = ', ';
	    	if ( sg_tag_check_settings("url") ) $link = 'tag-'.urlencode($tag[$i]).'.html';
			else $link = 'tags.php?tag='.urlencode($tag[$i]);
	    	$new['news_text'] .='<a href="'.$link.'">'.$tag[$i].'</a>'.$end;
	    	$i++;
		}
		$new['news_text'] .='</div>';
		return $new;
    } else {
    	return $new;
    }
}

function sg_tag_photoinfo($photo) {

    $tag = sg_tag_get_tag();
    if (is_array($tag)) {
		$start_tag = '<div class="tag">'; $end_tag = '</div>';
		$tekst = '<strong>Tagi:</strong> ';
		$i=0; $tags = '';
		while($i<count($tag)) {
	    	if ( $i+1 == count($tag) ) $end = '';
			else $end = ', ';
	    	if ( sg_tag_check_settings("url") ) $link = 'tag-'.urlencode($tag[$i]).'.html';
			else $link = 'tags.php?tag='.urlencode($tag[$i]);
	    	$tags .= '<a href="'.$link.'">'.$tag[$i].'</a>'.$end;
			$i++;
		}
		$tags = $start_tag.$tekst.$tags.$end_tag;
		return $tags;
    }
    return false;
}

function sg_tag_group() {

	global $db;
	$r = $db->select("SELECT COUNT(t.tag_name) as ile,t.*,f.photo_show,b.news_show FROM "._pre_."tags t LEFT JOIN "._pre_."blog b ON b.news_id=t.tag_for_id LEFT JOIN "._pre_."photo f ON f.photo_id = t.tag_for_id WHERE f.photo_show > 0 OR b.news_show > 0 GROUP BY t.tag_name HAVING COUNT(t.tag_name) ORDER BY RAND();");
	while($row = $db->get_row($r,'MYSQL_ASSOC')) {
		$tagi[] = $row;
	}
	return  $tagi;
}

function sg_tag_install() {

    global $db;
    $sql = 'CREATE TABLE IF NOT EXISTS `'._pre_.'tags` (
	`tag_id` int(10) unsigned NOT NULL auto_increment,
	`tag_name` varchar(100) default NULL,
	`tag_for` mediumint(8) default \'0\',
	`tag_for_id` mediumint(8) default \'0\',
	PRIMARY KEY  (`tag_id`)
	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;';
    $db->execute($sql);
	return;
}

function sg_tag_form_options($_POST) {

	global $db,$_GET;
	if ($_POST) {
		$dane = array('plugin_options'=>serialize($_POST));
		$db->update_array(_pre_."plugins",$dane,'plugin_id_file = \''.$_GET['options'].'\'');
	} else {
		$r=$db->select("SELECT * FROM "._pre_."plugins WHERE plugin_id_file = '".$_GET['options']."';");
		$row = $db->get_row($r,'MYSQL_ASSOC');
		$opcje = unserialize($row['plugin_options']);
		$select = array(0 => '', 1 => '', 2 => '', 3 => '');
		if ( $opcje['cloud'] == 0 ) $select[0] = ' selected="selected"';
		if ( $opcje['cloud'] == 1 ) $select[1] = ' selected="selected"';
		if ( $opcje['url'] == 0 ) $select[2] = ' selected="selected"';
		if ( $opcje['url'] == 1 ) $select[3] = ' selected="selected"';
		$form = '<form name="sg-tag-options" id="sg-tag-options" method="post" action="">
		<div class="form">
		<div class="l">
		<label name="cloud_label" for="cloud">'._("Chmurka tagów").':</label>
		<select name="cloud">
    	<option value="0"'.$select[0].'>wyłączona</option>
    	<option value="1"'.$select[1].'>włączona</option>
		</select>
		</div>
		</div>
		<div class="clr"></div>
		<div class="form"><div>Przyjazne URLe<br/>jeśli chcesz aby wtyczka <strong>Tagi</strong> wykorzystywała przyjazne adresy URL, dodaj poniższy wpis do pliku .htaccess</div><pre style="text-align:left; font-weight:normal;font-size:12px; background:#fff; color:#000; border:1px solid #ddd; padding:20px;margin:10px">RewriteRule ^tag-([^-]+).html$ tags.php?tag=$1 [L]</pre><strong>Pamiętaj, że ten wpis musi znajdować się PRZED tym:</strong><pre style="text-align:left; font-weight:normal;font-size:12px; background:#fff; color:#000; border:1px solid #ddd; padding:20px;margin:10px">RewriteRule ^([0-9a-z\-]+).html$ page.php?page=$1 [L]</pre>Zatem ostatnie dwie linijki powinny mieć postać<pre style="text-align:left; font-weight:normal;font-size:12px; background:#fff; color:#000; border:1px solid #ddd; padding:20px;margin:10px">RewriteRule ^tag-([^-]+).html$ tags.php?tag=$1 [L]
RewriteRule ^([0-9a-z\-]+).html$ page.php?page=$1 [L]</pre>
		<div class="l">
		<label name="urle" for="url">'._("Przyjazne URLe").':</label>
		<select name="url">
    	<option value="0"'.$select[2].'>wyłączone</option>
    	<option value="1"'.$select[3].'>włączone</option>
		</select>
		</div>
		</div>
		<div class="clr"></div>
		<div class="form">
		<div class="c">
		<input type="submit" name="send" value="'._("zapisz").'" class="button"/>
		</div>
		</div>
		<div class="clr"></div>
		</form>';
	}
	echo $form;
}

function sg_tag_get_tag() {

	global $db,$_GET;
	if ( $_GET['id'] ) $id = (int)$_GET['id'];
	if ( $_GET['idp'] && preg_match('/([a-z0-9]){32}/i',$_GET['idp']) ) {
    	$idp = $_GET['idp'];
    	$r = $db->select("SELECT photo_id FROM "._pre_."photo WHERE photo_file = '".$idp."' ORDER BY RAND();");
    	$photo = $db->get_row($r,'MYSQL_ASSOC');
    	$id = (int)$photo['photo_id'];
	}
	if ($id) {
    	$r = $db->select("SELECT * FROM "._pre_."tags WHERE tag_for_id = ".$id."  ORDER BY RAND()");
    	while( $row = $db->get_row($r,'MYSQL_ASSOC')) {
    		$tag[] = $row['tag_name'];
    	}
		return $tag;
	} elseif ($_GET['tag'] ) {
		$tag[] = urldecode($_GET['tag']); return $tag;
	} else {
		return null;
	}
}

function sg_tag_cloud_generate() {

	if ( sg_tag_check_settings("tag") ) {
		$tags = sg_tag_group();
		if ( count($tags) > 0 ) {
			require_once("TagCloudGenerator.inc.php");
			$tagCloudGenerator= new TagCloudGenerator();
			$i=0; $array_inside = ''; $array = array();
			while($i<count($tags)) {
				if ($i+1==count($tags)) $end = "\n";
				else $end = ",\n";
				if ( sg_tag_check_settings("url") ) {
    				$array[$i] =$tags[$i]['tag_name'].',tag-'.urlencode($tags[$i]['tag_name']).'.html,'.$tags[$i]['ile'].$end;
				} else {
    				$array[$i] =$tags[$i]['tag_name'].',tags.php?tag='.urlencode($tags[$i]['tag_name']).','.$tags[$i]['ile'].$end;
				}
				$i++;
			}
			$sidebar = '<h2>Tagi</h2>';
			$sidebar .= '<ul class="list tags"><li>'.$tagCloudGenerator->generateTagCloudFromArray($array).'</li></ul>';
			return $sidebar;
		}
	}
	return false;
}

function sg_tag_post($post="") {

	global $db, $_GET;
    $id = false;
    if ($post['id'] == 0) {
		$id = 0; $forwhat = 0;
    } elseif ($post['id']) {
		$id = $post['id'];
		if ($post['desc']) $forwhat = 1;
		else $forwhat = 0;
    }
	if ($_GET['id_photo'] ) {
	    $id = $_GET['id_photo'];
	    $forwhat = 1;
	}
	if ($_GET['id']) {
	    $id = $_GET['id'];
	    $forwhat = 0;
	}
    if ( $post && $post['tag']) {
		$key = explode(",",$post['tag']);
		if ($id)
		    $db->del("DELETE FROM "._pre_."tags WHERE tag_for_id = $id AND tag_for = $forwhat;");
		$i=0;
		while($i<count($key)) {
	    	$dane = array('tag_name' => trim($key[$i]),
			    'tag_for' => $forwhat,
			    'tag_for_id'=>$id);
	    	$db->insert_array(_pre_."tags",$dane);
	    	$i++;
		}
		return true;
    } else {
    	$r = $db->select("SELECT * FROM "._pre_."tags WHERE tag_for_id = ".$id." AND tag_for = ".$forwhat." ;");
    	while($row=$db->get_row($r,'MYSQL_ASSOC')) {
    		$tagi[] = $row['tag_name'];
    	}
    	if (is_array($tagi) ) {
    		$tags = join(', ',$tagi);
    	} else {
    		$tags = '';
    	}
		$form = '<div class="form">
	   	<label for="tag">'._("Tagi oddzielone przecinkami:").'</label>
	   	<input type="hidden" value="'.$forwhat.'" name="forwhat" />
	   	<input type="text" class="tag" name="tag" id="tag" value="'.$tags.'"/>
	   	</div>';
	   	return $form;
    }
    return false;
}

function sg_tag_check_settings($what=false) {

	global $db;
	$r = $db->select("SELECT * FROM "._pre_."plugins WHERE plugin_id_file = 'tags.plugin.php';");
	$op = $db->get_row($r, 'MYSQL_ASSOC');
	$opcje = unserialize($op['plugin_options']);
	switch($what) {
		case "url":
			if ($opcje['url'] == 1 ) return true;
			else return false;
		default;
		break;
		case "tag":
			if ($opcje['cloud'] == 1 ) return true;
			else return false;
		break;
	}
	return false;
}
?>
